import React from 'react'
import { Table,Popconfirm,Button, Switch } from 'antd';
import * as conf from './config';
import {Link} from 'react-router';
// import html2canvas from 'html2canvas';

class App extends React.Component {

  /**
   * 设置初始值
   * @param props
   */
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      pagination: {
        defaultPageSize:conf.pageNumber,  //默认每页显示条数
        currentPage:1,  //当前页
      },
      data:[],
      params:{
        table:'m1',
        order:'createTime desc',
        where:{state:0}
      },
      src:'https://www.baidu.com/img/baidu_jgylogo3.gif',
    };
  }

  /**
   * 第一次渲染后执行
   */
  componentDidMount() {
    this.getList();
    //this.convertImgToBase64('http://image.ecs001.com/images/test/20170510/Pxt7_BjQIoaJ9lkSHjN4tbBw.png');
  }

  /**
   * 获取数据
   * @param params
   */
  getList=()=>{
    const params = this.state.params;
    params.currentPage = this.state.pagination.currentPage;
    params.pageNumber = this.state.pagination.defaultPageSize;
    this.setState({ loading: true });
    conf.request(conf.action.list,params).then((result) => {
      if(result.errno == '0'){
        let data = result.data;
        const pagination = this.state.pagination;
        pagination.total = data.count; //获取总记录，设置分页
        this.setState({
          loading:false,
          data:data.data
        });
      }else{
        conf.tips('error','数据获取失败!',result.errmsg);
      }
    });
  };

  /**
   * 单个删除
   * @param id
   */
  del=(id)=>{
    this.setState({ loading: true });
    conf.request(conf.action.del,{
      table:this.state.params.table,
      where:{_id:id}
    }).then((result) => {
      conf.tips(result);
      this.setState({ loading: false });
      this.getList();
    });
  };

  /**
   * 批量删除
   */
  batchDel=()=>{
    this.setState({ loading: true });
    conf.request(conf.action.batchDel,{
      table:this.state.params.table,
      id:this.state.selectedRowKeys
    }).then((result) => {
      conf.tips(result);
      this.getList();
    });
  };

  /**
   * 点击分页，选择分类、事件
   * @param pagination
   * @param filters
   */
  handleTableChange = (pagination, filters) => {
    //筛选分类,按名称筛选
    let params = this.state.params;
    let where = params.where;
    for(let item in filters) {
      if(item == 'recommend'){
        if(filters[item][0] == 1){
          where[item] = true;
        }else{
          where[item] = false;
        }
      }else{
        where[item] = filters[item][0];  //每个分类只能单选，勾选多个无效
      }

    }
    params.where = where;
    //获取当前点击页
    let page = this.state.pagination;
    page.currentPage = pagination.current;
    this.setState({
      pagination:page,
      params:params
    });
    this.getList();
  };

  /**
   * 复选框改变事件
   * @param selectedRowKeys
   */
  onSelectChange = (selectedRowKeys) => {
    console.log(selectedRowKeys);
    this.setState({
      selectedRowKeys:selectedRowKeys
    });
  };

  /**
   * 推荐开关
   * @param id
   * @param checked
   */
  switchOnChange=(id,checked)=>{
    // console.log(id,checked);
    this.update({
      table:'m1',
      where:{_id:id},
      recommend:checked,
    })
  };

  /**
   * 更新
   * @param params
   */
  update=(params={})=>{
    this.setState({ loading: true });
    conf.request(conf.action.update,params).then((result)=>{
      // console.log(result);
      conf.tips(result);
      this.setState({
        loading: false,
      });
      this.getList();
    })
  };


  // findActive(){
  //   conf.request(conf.action.findActive,{
  //     table:'m4'
  //   }).then((result)=>{
  //     console.log(result);
  //   })
  // }

  // imageSyn=()=>{
  //   this.setState({ loading: true });
  //   let w = document.body.scrollWidth;
  //   let h = document.body.scrollHeight;
  //   let canvas = document.createElement("canvas");
  //   canvas.width = w * 2;
  //   canvas.height = h * 2;
  //   let context = canvas.getContext("2d");
  //   context.scale(2, 2);
  //   html2canvas($('body'), {
  //     canvas: canvas,
  //     onrendered: function (canvas) {
  //       let dataUrl = canvas.toDataURL("image/png");
  //       let newImg = new Image;
  //       newImg.src = dataUrl;
  //       newImg.width = w;
  //       $('body').html(newImg);
  //     },useCORS:true
  //   });
  //   this.setState({ loading: false });
  // };

  //canvas绘图
  // canvasImageSyn=()=>{
  //   this.setState({ loading: true });
  //   let img = new Image,
  //     canvas = document.createElement("canvas"),
  //     ctx = canvas.getContext("2d"),
  //     src = "http://image.ecs001.com/images/m4/20170510/ivtUnQEwUUPJbcS7BOgLpTRu.jpg"; // insert image url here
  //   img.crossOrigin = "Anonymous";
  //   let qrCode = new Image;
  //   qrCode.src = ''; //填写活动的二维码地址
  //   img.onload = function() {
  //      canvas.width = img.width;
  //      canvas.height = img.height;
  //      ctx.drawImage( img, 0, 0 );
  //      ctx.drawImage( qrCode, 0, 0 );
  //      ctx.font="30px Arial";
  //      ctx.fillText("Hello World",200,50);
  //      img.src = canvas.toDataURL("image/png");
  //   };
  //   this.setState({ loading: false });
  //   img.src = src;
  //   $('body').append(img);
  // };


  /**
   * 渲染模版
   * @returns {XML}
   */
  render() {
    console.log(this.state.src);
    const columns = [
      {title: '图片名称',
        dataIndex: 'title',
        width: '20%',
      },{
        title: '',
        width: '25%',
      },{
        title: '',
        dataIndex: 'picture',
        width: '10%',
        render:(text, record,)=>{
          return(
            <img src={record.picture} style={{width:30,height:30}}/>
          );
        }
      }, {
        title: '是否推荐',
        dataIndex: 'recommend',
        width: '10%',
        filters: [
          { text: '推荐', value: 1 },
          { text: '所有', value: 0},
        ],
        render:(text, record,)=>{
          return(
            <Switch defaultChecked={record.recommend} onChange={this.switchOnChange.bind(this,record._id)} />
          );
        }
      },{
        title: '添加时间',
        dataIndex: 'createTime',
        width: '10%',
      },{
        title: '状态',
        dataIndex: 'stateRemark',
        width: '10%',
      },{
        title: '操作',
        width: '10%',
        render: (text, record, index) => {
          const id = record._id;
          const url = '/admin/edit/'+id;
          return (
            <div>
              <Link to={url}>编辑</Link>
              <Popconfirm title="确定删除?" onConfirm={() => this.del(id)}>
                <Link style={{paddingLeft:10}}>删除</Link>
              </Popconfirm>
            </div>
          );
        }
      }
    ];

    const rowSelection = {
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          rowKey={record => record._id}
          dataSource={this.state.data}
          pagination={this.state.pagination}
          loading={this.state.loading}
          onChange={this.handleTableChange}
          footer={() =>  <Button onClick={this.batchDel}>删除</Button>}
        />
      </div>
    );
  }
}

export default App;